package com.analysis.interceptor;

import com.analysis.enums.RequireLogin;
import com.analysis.dto.ApiResponse;
import com.analysis.entity.User;
import com.analysis.utils.RedisSessionManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 认证拦截器
 * 验证用户登录状态
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {
    
    @Autowired
    private RedisSessionManager sessionManager;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 只拦截Controller方法
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        
        // 检查方法上是否有@RequireLogin注解
        RequireLogin requireLogin = method.getAnnotation(RequireLogin.class);
        if (requireLogin == null) {
            // 检查类上是否有@RequireLogin注解
            requireLogin = method.getDeclaringClass().getAnnotation(RequireLogin.class);
        }
        
        // 如果没有@RequireLogin注解，直接放行
        if (requireLogin == null || !requireLogin.required()) {
            return true;
        }
        
        // 获取token
        String token = getTokenFromRequest(request);
        
        // 验证token
        if (token == null || !sessionManager.isValidToken(token)) {
            // 未登录，返回错误信息
            writeErrorResponse(response, requireLogin.message());
            return false;
        }
        
        // 将用户信息存储到request中，供后续使用
        User user = sessionManager.getUserByToken(token);
        request.setAttribute("currentUser", user);
        request.setAttribute("userToken", token);
        
        return true;
    }
    
    /**
     * 从请求中获取token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        // 优先从Header中获取
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            return token.substring(7);
        }
        
        // 从Header中获取token
        token = request.getHeader("token");
        if (token != null) {
            return token;
        }
        
        // 从参数中获取token
        token = request.getParameter("token");
        if (token != null) {
            return token;
        }
        
        return null;
    }
    
    /**
     * 写入错误响应
     */
    private void writeErrorResponse(HttpServletResponse response, String message) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        
        ApiResponse<Object> apiResponse = ApiResponse.error(message);
        String jsonResponse = objectMapper.writeValueAsString(apiResponse);
        
        response.getWriter().write(jsonResponse);
    }
}
